﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using web.core.ViewModels;
using web.core.Models;
using web.component;
using System.Configuration;
using web.data.entities;

namespace web.core.Controllers
{
    public class admAccountController : baseController
    {
        #region login/logout
        public ActionResult login()
        {
            return View();
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult control_login()
        {
            var login = new ViewModels.LoginViewModels();
            HttpCookie ck = HttpContext.Request.Cookies["Sercurity_User"];
            if (ck != null )
            {
                login.username = ck.Values["username"];
                login.password = ck.Values["password"];
                login.remember = bool.Parse(ck.Values["remember"]??"true");
            }
            return PartialView("../Shared/control_login",login);
        }

        [ChildActionOnly]
        [HttpPost]
        public ActionResult control_login(FormCollection values)
        {
            cryptography_component cryCom=new cryptography_component();
            string olUrl = Request.UrlReferrer.AbsoluteUri;
            string redirectStr = "";
            int user_id = 0;
            var login = new ViewModels.LoginViewModels();
            TryUpdateModel(login);

            if ((login.username == null && login.password == null) || login.username == null || login.password == null)
            {
                ViewBag.login = false;
                return PartialView("../Shared/control_login", login);
            }

            try
            {
                string _password = cryCom.MD5(login.password);
                string _salt = _password.Substring(0, 5);
                string _cryptography_password=System.Configuration.ConfigurationManager.AppSettings["CryptographyPassword"].ToString();
                string _initial_vector=System.Configuration.ConfigurationManager.AppSettings["InitialVector"].ToString();
                string pass=cryCom.Encrypt(_password,_cryptography_password , _salt, _initial_vector);
                var user = accountModels.authenticateUser(login.username, pass);
                if (user != null)
                {
                    user_id = user.user_id;
                }
                 
                if (user_id > 0)
                {
                    Session["user_id"] = user_id;
                    
                    if (login.remember)
                    {
                        HttpCookie ck = new HttpCookie("Sercurity_User");
                        ck.Values["username"] = login.username;
                        ck.Values["password"] = login.password;
                        ck.Values["user_id"] = user_id.ToString();
                        ck.Values["remember"] = login.remember.ToString();
                        ck.Expires = DateTime.Now.AddDays(1);//Thoi han luu cookie
                        HttpContext.Response.Cookies.Add(ck);

                    }
                    
                   
                    //Ghi lại log SignIn
                                      
                    if (Session["next_action"] != null)
                    {
                        redirectStr = Session["next_action"].ToString();
                    }
                    else
                    {
                        if(olUrl!=string.Empty)
                        {
                            if (olUrl.Contains("/admAccount/login"))
                            {
                                redirectStr = "/" + DefaultLanguageGetter() + ConfigurationManager.AppSettings["DefaultPage"].ToString();   //"/dashboard/index"
                            }
                            else
                                redirectStr=olUrl;
                        }
                       
                    }   
                }
                else
                {
                    Session["user_id"] = null;
                    ViewBag.login=false;
                    return PartialView("../Shared/control_login", login);
                }
            }
            catch(Exception ex)
            {
                Response.Write(ex);
                Session["user_id"] = null;
                ViewBag.login=false;
                return PartialView("../Shared/control_login", login);
            }
            ViewBag.redirect=redirectStr;
            ViewBag.login=true;
            return PartialView("../Shared/control_redirect");
        }
       
        public ActionResult logout()
        {
            Session["user_id"] = null;
            return RedirectToAction("login", "admAccount");
        }
        #endregion

        #region change_password
        public ActionResult change_password()
        {
            bool permission = false;
            InitPage(ref permission);
            ViewBag.permission = permission;
            return View();
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult control_change_password()
        {
            return PartialView("../Shared/user/control_change_password");
        }

        [ChildActionOnly]
        [HttpPost]
        public ActionResult control_change_password(FormCollection values) 
        {
            cryptography_component cryCom = new cryptography_component();
            var change = new ViewModels.ChangePasswordViewModels();
            TryUpdateModel(change);

            if (change.password == null)
            {
                ViewBag.result_message = "Xin vui lòng nhập mật khẩu.";
                ViewBag.result = false;
                return PartialView("../Shared/user/control_change_password");
            }

            if (change.new_password == null)
            {
                ViewBag.result_message = "Xin vui lòng nhập mật khẩu mới.";
                ViewBag.result = false;
                return PartialView("../Shared/user/control_change_password");
            }

            if (change.confirm_password == null)
            {
                ViewBag.result_message = "Xin vui lòng xác nhận mật khẩu mới.";
                ViewBag.result = false;
                return PartialView("../Shared/user/control_change_password");
            }

            try
            {
                string _password = cryCom.MD5(change.password);
                string _salt = _password.Substring(0, 5);
                string _cryptography_password = System.Configuration.ConfigurationManager.AppSettings["CryptographyPassword"].ToString();
                string _initial_vector = System.Configuration.ConfigurationManager.AppSettings["InitialVector"].ToString();
                string pass = cryCom.Encrypt(_password, _cryptography_password, _salt, _initial_vector);
                if (accountModels.getUserByID(int.Parse(Session["user_id"].ToString())).password.Equals(pass))
                {
                    if (change.new_password.Equals(change.confirm_password))
                    {
                        var user = accountModels.getUserByID(int.Parse(Session["user_id"].ToString()));
                        user.password = cryCom.Encrypt(cryCom.MD5(change.new_password), _cryptography_password, cryCom.MD5(change.new_password).Substring(0, 5), _initial_vector);
                        user.salt = cryCom.MD5(change.new_password).Substring(0, 5);
                        accountModels.changePassword(user);
                    }
                    else
                    {
                        ViewBag.result_message = "Mật khẩu xác nhận không đúng.";
                        ViewBag.result = false;
                    }
                }
                else
                {
                    ViewBag.result_message = "Mật khẩu không hợp lệ.";
                    ViewBag.result = false;
                }
            }
            catch(Exception ex)
            {
                ViewBag.result_message = ""+ex.Message;
                ViewBag.result = false;
                return PartialView("../Shared/user/control_change_password");
            }
            ViewBag.result_message = "Thay đổi mật khẩu thành công.";
            ViewBag.result = true;
            return PartialView("../Shared/user/control_change_password");
        }
        #endregion

        #region forgot_password
        public ActionResult forgot_password()
        {
            return View();
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult ctr_forgot_password()
        {
            var forgot = new ViewModels.ForgotPasswordViewModels();
            HttpCookie ck = HttpContext.Request.Cookies["Sercurity_User"];
            if (ck != null)
            {
                forgot.username = ck.Values["username"];
            }
            return PartialView("../Shared/user/control_forgot_password", forgot);
        }

        [ChildActionOnly]
        [HttpPost]
        public ActionResult ctr_forgot_password(FormCollection collection)
        {
            cryptography_component cryCom = new cryptography_component();
            web.component.email_component email_com = new email_component();
            var forgot = new ViewModels.ForgotPasswordViewModels();
            TryUpdateModel(forgot);
            try
            {
                var user = accountModels.authenticateAdmForgotPassword(forgot.username, forgot.email);

                int userForgot = user != null ? user.user_id : 0;
                if (userForgot > 0)
                {
                    var ustring = new Ustring();
                    string newPassword = ustring.RandomString(6, true);
                    string _password = cryCom.MD5(newPassword);
                    string _salt = _password.Substring(0, 5);
                    string _cryptography_password = System.Configuration.ConfigurationManager.AppSettings["CryptographyPassword"].ToString();
                    string _initial_vector = System.Configuration.ConfigurationManager.AppSettings["InitialVector"].ToString();
                    string pass = cryCom.Encrypt(_password, _cryptography_password, _salt, _initial_vector);

                    user.password = pass;

                      //get content email forgot password
                    var mail_id = global_const.EMAIL_ID_FORGOT_PASSWORD;
                    var lst_content = new List<EmailVariable>()
                                  {
                                      new EmailVariable("password", newPassword)
                                  };
                    var check_send_email_password = SendWebEmail(mail_id, lst_content, forgot.email, "", "");

                    // cap nhat lai thong tin
                    if (check_send_email_password)
                    {
                        user.salt = cryCom.MD5(newPassword).Substring(0, 5);
                        accountModels.changePassword(user);
                    }
                }
            }
            catch
            {
                return PartialView("../Shared/user/control_forgot_password", forgot);
            }
            return PartialView("../Shared/user/control_forgot_password", forgot);
        }
        #endregion

        #region list_user
        public ActionResult list_user()
        {
            bool permission = false;
            InitPage(ref permission);
            ViewBag.permission = permission;
            return View();
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult control_list_user(int? id, string text_search, int? group_id)
        {
            return control_list_user(id ?? 1, 10, text_search, group_id);
        }

        [ChildActionOnly]
        [HttpPost]
        public ActionResult control_list_user(int? id,int? pagesize, string text_search, int? group_id)
        {
            var lstdelete = Request.Form["is_delete"];
            if (!string.IsNullOrEmpty(lstdelete))
            {
                var arr = lstdelete.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var iterator in arr)
                {
                    if (iterator != "false")
                        accountModels.UserDelete(Convert.ToInt32(iterator));
                }
            } 

            List<SelectListItem> sizeDrop = new List<SelectListItem>();
            sizeDrop.AddRange(new SelectListItem[] { 
                            new SelectListItem{Selected=pagesize==10?true:false, Text = "10", Value = "10" },
                            new SelectListItem{Selected=pagesize==25?true:false, Text = "25", Value = "25" },
                            new SelectListItem{Selected=pagesize==50?true:false, Text = "50", Value = "50" },
                            new SelectListItem{Selected=pagesize==100?true:false, Text = "100", Value = "100" }
                        }); 

            var page_view = new ViewModels.PageListUserViewModels();
            id = id ?? 1;
            page_view.list_group = accountModels.getListUserGroup();
            page_view.list_pagesize = sizeDrop;
            page_view.pagesize = pagesize??10;
            page_view.page_list_user = Models.accountModels.getPageListUser(id ?? 1, pagesize??10, text_search ?? null, group_id);
            return PartialView("../Shared/user/control_list_user", page_view);
        }

        public ActionResult updateStatusUser(string id)
        {
            web.data.entities.users user = new data.entities.users();
            user.user_id = int.Parse(id.Split(',')[0]);
            user.user_status = byte.Parse(id.Split(',')[1]);
            Models.accountModels.updateStatusUser(user);

            string outStr = "" + user.user_status;
            return Json(outStr);
        }

        #endregion

        #region add/ edit_user
        public ActionResult edit_user()
        {
            bool permission = false;
            InitPage(ref permission);
            ViewBag.permission = permission;
            return View();
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult control_edit_user(int? id)
        {

            var user_view = new ViewModels.UserViewModels();
            user_view.listGroupUser = accountModels.getListUserGroup();
            var user = accountModels.getUserByID(id ?? 0);
            if (user != null)
            {
                //edit
                ViewBag.isAdd = false;
                user_view.user_id = user.user_id;
                user_view.username = user.username;
                user_view.user_status = user.user_status;
                user_view.active_date = user.active_date;
                user_view.created_date = user.created_date;
                user_view.email = user.email;
                user_view.listGroupUser = accountModels.getListUserGroup();
                var list_arr = accountModels.getListGroupOfUser(id ?? 0).ToList();
                for (int i = 0; i < list_arr.Count(); i++)
                {
                    user_view.arr_group_id = user_view.arr_group_id + list_arr[i].ToString() + ",";
                }

                if (user_view.arr_group_id != null && user_view.arr_group_id.EndsWith(","))
                {
                    user_view.arr_group_id = user_view.arr_group_id.Substring(0, user_view.arr_group_id.LastIndexOf(","));
                }
            }
            else
            {
                //add
                ViewBag.isAdd = true;
                user_view.user_status = 1;
            }

            return PartialView("../Shared/user/control_detail_user", user_view);
        }

        [ChildActionOnly]
        [HttpPost]
        public ActionResult control_edit_user(FormCollection collection)
        {
            var user_view = new ViewModels.UserViewModels();
            TryUpdateModel(user_view);

            if (string.IsNullOrEmpty(user_view.username))
            {
                ViewBag.result_message = "Xin vui lòng nhập username.";
                ViewBag.result = false;
                return PartialView("../Shared/user/control_detail_user",user_view);
            }

            if (string.IsNullOrEmpty(user_view.email))
            {
                ViewBag.result_message = "xin vui lòng nhập email.";
                ViewBag.result = false;
                return PartialView("../Shared/user/control_detail_user", user_view);
            }

            cryptography_component cryCom = new cryptography_component();
            string _password = "";
            string _salt = "";
            string _cryptography_password = "";
            string _initial_vector = "";
            string pass = "";
            if (!string.IsNullOrEmpty(user_view.password) && !string.IsNullOrEmpty(user_view.confirm_password))
            {
                _password = cryCom.MD5(user_view.password);
                _salt = _password.Substring(0, 5);
                _cryptography_password = System.Configuration.ConfigurationManager.AppSettings["CryptographyPassword"].ToString();
                _initial_vector = System.Configuration.ConfigurationManager.AppSettings["InitialVector"].ToString();
                pass = cryCom.Encrypt(_password, _cryptography_password, _salt, _initial_vector);
            }
            bool isadd = (user_view.user_id != 0 && user_view.user_id != null) ? false : true;
            bool isok = false;
            int retid = 0;
            if (!isadd)
            {
                var user = accountModels.getUserByID(user_view.user_id ?? 0);
                user.username = user_view.username;
                user.user_status = user_view.user_status;
                user.email = user_view.email;
                if (!string.IsNullOrEmpty(_password))
                {
                    user.password = pass;
                }
                user.salt = _salt;
                accountModels.editUser(user);

                isok = true;
                retid = user.user_id;
                ////update group of user
                ////delete all group of user
                //accountModels.deleteAllGroupOfUser(user.user_id);
                //if (!string.IsNullOrEmpty(user_view.arr_group_id))
                //{
                //    var arr = user_view.arr_group_id.Split(',');
                //    var arrs = arr.ToList();
                //    if (arrs.Count > 0)
                //    {

                //        if (arrs[0] != "System.Int32[]")
                //        {
                //            for (int i = 0; i < arr.Length; i++)
                //            {

                //                //add new list group for user
                //                if (!string.IsNullOrEmpty(arrs[i]))
                //                {
                //                    accountModels.addGroupForUser(int.Parse(arrs[i]), user.user_id);
                //                }
                //            }
                //        }

                //    }
                //}

                //ViewBag.result_message = "Cập nhật user thành công.";
                //ViewBag.result = true;
                //ViewBag.redirect = "/vi/admAccount/list_user";
                //return PartialView("../Shared/control_redirect");
            }
            else {
                var user = new data.entities.users()
                {
                    username = user_view.username,
                    user_status = user_view.user_status,
                    email = user_view.email,
                    created_date = Udate_time.GetCurrentDateTime(),
                    password = pass,
                    salt = _salt,
                    activation_code = null,
                    active_date = Udate_time.GetCurrentDateTime()
                };

                retid = accountModels.createUser(user);
                isok =  true;
                //if (retid > 0)
                //{
                //    //add group for user
                //    if (!string.IsNullOrEmpty(user_view.arr_group_id))
                //    {
                //        var arr = user_view.arr_group_id.Split(',');
                //        foreach (var item in arr)
                //        {
                //            if (!string.IsNullOrEmpty(item))
                //            {
                //                accountModels.addGroupForUser(int.Parse(item.ToString()), retid);
                //            }
                //        }
                //    }
                //    ViewBag.result_message = admin_const.UPDATE_OK;
                //    ViewBag.result = true;
                //    ViewBag.redirect = "/vi/admAccount/list_user";
                //    return PartialView("../Shared/control_redirect");
                    
                //}
                //else
                //{
                //    ViewBag.result_message = "Thêm mới người dùng thất bại.";
                //    ViewBag.result = false;
                //    return PartialView("../Shared/user/control_detail_user", user_view);
                //}
            }

            //update group of user
            if (isadd ==false && isok==true && retid >0) {
                //delete all group of user
                accountModels.deleteAllGroupOfUser(retid);                
            }
            if (isok == true && retid > 0)
            {
                if (!string.IsNullOrEmpty(user_view.arr_group_id))
                {
                    var arr = user_view.arr_group_id.Split(',');
                    var arrs = arr.ToList();
                    if (arrs.Count > 0)
                    {

                        if (arrs[0] != "System.Int32[]")
                        {
                            for (int i = 0; i < arr.Length; i++)
                            {

                                //add new list group for user
                                if (!string.IsNullOrEmpty(arrs[i]))
                                {
                                    accountModels.addGroupForUser(int.Parse(arrs[i]), retid);
                                }
                            }
                        }

                    }
                }
                ViewBag.result_message = admin_const.UPDATE_OK;
                ViewBag.result = true;
                ViewBag.redirect = "/vi/admAccount/list_user";
                return PartialView("../Shared/control_redirect");
            }
            else {
                ViewBag.result_message = admin_const.UPDATE_FAIL;
                ViewBag.result = false;
                return PartialView("../Shared/user/control_detail_user", user_view);
            }

        }

        //public ActionResult add_user()
        //{
        //    bool permission = false;
        //    InitPage(ref permission);
        //    ViewBag.permission = permission;
        //    return View();
        //}

        //[ChildActionOnly]
        //[HttpGet]
        //public ActionResult control_add_user()
        //{
        //    ViewBag.isAdd = true;
        //    var user_view = new ViewModels.UserViewModels();
        //    user_view.user_status = 1;
        //    user_view.listGroupUser = accountModels.getListUserGroup();
        //    return PartialView("../Shared/user/control_detail_user", user_view);
        //}

        //[ChildActionOnly]
        //[HttpPost]
        //public ActionResult control_add_user(FormCollection collection)
        //{
        //    var user_view = new ViewModels.UserViewModels();
        //    TryUpdateModel(user_view);

        //    cryptography_component cryCom = new cryptography_component();
        //    string _password = cryCom.MD5(user_view.password);
        //    string _salt = _password.Substring(0, 5);
        //    string _cryptography_password = System.Configuration.ConfigurationManager.AppSettings["CryptographyPassword"].ToString();
        //    string _initial_vector = System.Configuration.ConfigurationManager.AppSettings["InitialVector"].ToString();
        //    string pass = cryCom.Encrypt(_password, _cryptography_password, _salt, _initial_vector);

        //    var user = new data.entities.users()
        //    {
        //        username = user_view.username,
        //        user_status = user_view.user_status,
        //        email = user_view.email,
        //        created_date = Udate_time.GetCurrentDateTime(),
        //        password = pass,
        //        salt = _salt,
        //        activation_code = null,
        //        active_date = Udate_time.GetCurrentDateTime()
        //    };
            
        //    int new_id= accountModels.createUser(user);

        //    if (new_id > 0)
        //    {
        //        //add group for user
        //        if (!string.IsNullOrEmpty(user_view.arr_group_id))
        //        {
        //            var arr = user_view.arr_group_id.Split(',');
        //            foreach (var item in arr)
        //            {
        //                if (!string.IsNullOrEmpty(item))
        //                {
        //                    accountModels.addGroupForUser(int.Parse(item.ToString()), new_id);
        //                }
        //            }
        //        }

        //        ViewBag.result_message = "Thêm mới người dùng thành công.";
        //        ViewBag.result = true;
        //        ViewBag.redirect = "/vi/admAccount/list_user";
        //        return PartialView("../Shared/control_redirect");
        //    }
        //    else 
        //    {
        //        ViewBag.result_message = "Thêm mới người dùng thất bại.";
        //        ViewBag.result = false;
        //        return PartialView("../Shared/user/control_detail_user", user_view);
        //    }
            
            
        //}
        #endregion

        #region list_group
        public ActionResult list_group()
        {
            bool permission = false;
            InitPage(ref permission);
            ViewBag.permission = permission;
            return View();
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult control_list_group(int? id, string text_search)
        {
            return control_list_group(id ?? 1, 10, text_search);
        }

        [ChildActionOnly]
        [HttpPost]
        public ActionResult control_list_group(int? id, int? pagesize, string text_search)
        {          
            var group_view = new ViewModels.PageListGroupViewModels();
            id = id ?? 1;
            group_view.list_pagesize = GetSizePagingPublic(pagesize??10);
            group_view.pagesize = pagesize ?? 10;
            group_view.page_list_group = Models.accountModels.getPageListGroup(id ?? 1, pagesize ?? 10, text_search ?? null);
            return PartialView("../Shared/user/control_list_group", group_view);
        }
        
        public ActionResult updateStatusGroup(string id)
        {
            web.data.entities.user_group group = new data.entities.user_group();
            group.group_id = int.Parse(id.Split(',')[0]);
            group.group_enable = bool.Parse(id.Split(',')[1]);
            Models.accountModels.updateStatusGroup(group);

            string outStr = "" + group.group_enable;
            return Json(outStr);
        }
        #endregion

        #region list_page
        public ActionResult list_page()
        {
            bool permission = false;
            InitPage(ref permission);
            ViewBag.permission = permission;
            return View();
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult control_list_page(int? id, string text_search, int? parent)
        {
            return control_list_page(id ?? 1, 10, text_search,parent);
        }

        [ChildActionOnly]
        [HttpPost]
        public ActionResult control_list_page(int? id, int? pagesize, string text_search, int? parent)
        {
            var page_view = new ViewModels.PageListPageViewModels();
            id = id ?? 1;
            page_view.list_pagesize = GetSizePagingPublic(pagesize ?? 10);
            page_view.pagesize = pagesize ?? 10;
            page_view.list_page_parent = accountModels.getListPageByParent(null);
            //page_view.list_page_parent.Add(new page { page_id = 0, page_name = "Tất cả" });
            page_view.parent = parent ?? 0;
            page_view.page_list_page = accountModels.getPagerBuilder(id ?? 1, pagesize ?? 10, text_search ?? null, parent);

            return PartialView("../Shared/page/control_list_page", page_view);
        }

        public ActionResult updateStatusPage(string id)
        {
            web.data.entities.page page = new data.entities.page();
            page.page_id = int.Parse(id.Split(',')[0]);
            page.page_status = byte.Parse(id.Split(',')[1]);
            Models.accountModels.updateStatusPage(page);

            string outStr = "" + page.page_status;
            return Json(outStr);
        }
        #endregion

        #region add/ edit page
        public ActionResult add_page()
        {
            bool permission = false;
            InitPage(ref permission);
            ViewBag.permission = permission;
            return View();
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult control_add_page(int? id)
        {
            ViewBag.isAdd = true;
            var page_view = new ViewModels.PageViewModels();
            page_view.page_status = 1;
            page_view.listPageParent = accountModels.getListPageBuilder(null);
            if(id!=null){
                page_view.page_parent = id;
            }
            return PartialView("../Shared/page/control_detail_page", page_view);
        }

        [ChildActionOnly]
        [HttpPost]
        public ActionResult control_add_page(FormCollection collection)
        {
            var page_view = new ViewModels.PageViewModels();
            TryUpdateModel(page_view);

            web.data.entities.page page = new data.entities.page();
            page.page_name = page_view.page_name;
            page.page_desc = page_view.page_desc;
            page.page_path = page_view.page_path;
            page.page_status = page_view.page_status;
            page.page_type = page_view.page_type;
            page.page_order = page_view.page_order;
            page.page_parent = page_view.page_parent;

            int new_id = accountModels.createPage(page);

            if (new_id > 0)
            {
                ViewBag.result_message = "Thêm mới page thành công.";
                ViewBag.result = true;
                ViewBag.redirect = "/vi/admAccount/list_page";
                return PartialView("../Shared/control_redirect");
            }
            else
            {
                ViewBag.isAdd = true;
                ViewBag.result_message = "Thêm mới page thất bại.";
                ViewBag.result = false;
                return PartialView("../Shared/page/control_detail_page", page_view);
            }
        }

        public ActionResult edit_page()
        {
            bool permission = false;
            InitPage(ref permission);
            ViewBag.permission = permission;
            return View();
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult control_edit_page(int? id)
        {
            ViewBag.isAdd = false;
            var page_view = new ViewModels.PageViewModels();
            var page = accountModels.getPageByID(id ?? 0);
            page_view.page_id = page.page_id;
            page_view.page_name = page.page_name;
            page_view.page_path = page.page_path;
            page_view.page_status = page.page_status;
            page_view.page_desc = page.page_desc;
            page_view.page_order = page.page_order;
            page_view.listPageParent = accountModels.getListPageBuilder(null);
            page_view.page_parent = page.page_parent;
            return PartialView("../Shared/page/control_detail_page", page_view);
        }

        [ChildActionOnly]
        [HttpPost]
        public ActionResult control_edit_page(FormCollection collection)
        {
            var page_view = new ViewModels.PageViewModels();
            TryUpdateModel(page_view);

            if (string.IsNullOrEmpty(page_view.page_name))
            {
                ViewBag.isAdd = false;
                ViewBag.result_message = "Xin vui lòng nhập tên page.";
                ViewBag.result = false;
                return PartialView("../Shared/page/control_detail_page", page_view);
            }

            var page = accountModels.getPageByID(page_view.page_id ?? 0);
            page.page_id = (int)page_view.page_id;
            page.page_name = page_view.page_name;
            page.page_path = page_view.page_path;
            page.page_status = page_view.page_status;
            page.page_desc = page_view.page_desc;
            page.page_order = page_view.page_order;
            page.page_parent = page_view.page_parent;

            accountModels.editPage(page);

            ViewBag.result_message = "Cập nhật page thành công.";
            ViewBag.result = true;
            ViewBag.redirect = "/vi/admAccount/list_page";
            return PartialView("../Shared/control_redirect");
        }
        #endregion

        #region add/ edit group 
        public ActionResult add_group()
        {
            bool permission = false;
            InitPage(ref permission);
            ViewBag.permission = permission;
            return View();
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult control_add_group(int? id)
        {
            ViewBag.isAdd = true;
            var group_view = new ViewModels.GroupViewModels();
            group_view.group_enable = true;
            group_view.listGroupParent = accountModels.getListGroupBuilder(null);
            if (id != null)
            {
                group_view.group_parent_id = id;
            }
            return PartialView("../Shared/user/control_detail_group", group_view);
        }

        [ChildActionOnly]
        [HttpPost]
        public ActionResult control_add_group(FormCollection collection)
        {
            var group_view = new ViewModels.GroupViewModels();
            TryUpdateModel(group_view);

            web.data.entities.user_group group = new data.entities.user_group();
            group.group_name = group_view.group_name;
            group.group_desc = group_view.group_desc;
            group.group_enable = group_view.group_enable;
            group.group_parent_id = group_view.group_parent_id;

            int new_id = accountModels.createGroup(group);

            if (new_id > 0)
            {
                ViewBag.isAdd = true;
                ViewBag.result_message = "Thêm nhóm mới thành công.";
                ViewBag.result = true;
                ViewBag.redirect = "/vi/admAccount/list_group";
                return PartialView("../Shared/control_redirect");
            }
            else
            {
                ViewBag.isAdd = true;
                ViewBag.result_message = "Thêm mới nhóm thất bại.";
                ViewBag.result = false;
                return PartialView("../Shared/user/control_detail_group", group_view);
            }
        }

        public ActionResult edit_group()
        {
            bool permission = false;
            InitPage(ref permission);
            ViewBag.permission = permission;
            return View();
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult control_edit_group(int? id)
        {
            ViewBag.isAdd = false;
            var group_view = new ViewModels.GroupViewModels();
            var group = accountModels.getGroupByID(id ?? 0);
            group_view.group_id = group.group_id;
            group_view.group_name = group.group_name;
            group_view.group_desc = group.group_desc;
            group_view.group_enable = group.group_enable;
            group_view.group_parent_id = group.group_parent_id;
            group_view.listGroupParent = accountModels.getListGroupBuilder(null);
            return PartialView("../Shared/user/control_detail_group", group_view);
        }

        [ChildActionOnly]
        [HttpPost]
        public ActionResult control_edit_group(FormCollection collection)
        {
            var group_view = new ViewModels.GroupViewModels();
            TryUpdateModel(group_view);

            if (string.IsNullOrEmpty(group_view.group_name))
            {
                ViewBag.isAdd = false;
                ViewBag.result_message = "Xin vui lòng nhập tên nhóm.";
                ViewBag.result = false;
                return PartialView("../Shared/user/control_detail_group", group_view);
            }

            var group = accountModels.getGroupByID(group_view.group_id ?? 0);
            group.group_id = (int)group_view.group_id;
            group.group_name = group_view.group_name;
            group.group_desc = group_view.group_desc;
            group.group_enable = group_view.group_enable;
            group.group_parent_id = group_view.group_parent_id;

            accountModels.editGroup(group);

            ViewBag.result_message = "Cập nhật nhóm thành công.";
            ViewBag.result = true;
            ViewBag.redirect = "/vi/admAccount/list_group";
            return PartialView("../Shared/control_redirect");
        }
        #endregion

        #region access_page
        public ActionResult access_page()
        {
            bool permission = false;
            InitPage(ref permission);
            ViewBag.permission = permission;
            return View();
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult control_access_page(int? id, string text_search, int? parent,int? group_id)
        {
            return control_access_page(id ?? 1, 10, text_search, parent,group_id);
        }

        [ChildActionOnly]
        [HttpPost]
        public ActionResult control_access_page(int? id, int? pagesize, string text_search, int? parent, int? group_id)
        {
            var page_view = new ViewModels.PageListPageViewModels();
            id = id ?? 1;
            page_view.list_pagesize = GetSizePagingPublic(pagesize ?? 10); ;
            page_view.pagesize = pagesize ?? 10;
            page_view.page_list_page = accountModels.getPagerBuilder(id ?? 1, pagesize ?? 10, text_search ?? null, parent);
            page_view.list_page_parent = accountModels.getListPageByParent(null);
            page_view.list_page_access_by_group = accountModels.getListPageAccessByGroup(group_id??0);
            page_view.parent = parent??0;
            foreach (var items in page_view.list_page_access_by_group)
            {
                page_view.array_page_access = page_view.array_page_access + "," + items.ToString();
            }
            if (!string.IsNullOrEmpty(page_view.array_page_access))
            {
                if (page_view.array_page_access.StartsWith(","))
                {
                    page_view.array_page_access = page_view.array_page_access.Substring(1);
                }
            }
           
            return PartialView("../Shared/page/control_access_page", page_view);
        }

        public ActionResult save_access_page(string id)
        {
            var group_id = int.Parse(id.Split(';')[0]);
            var arr_access_page = id.Split(';')[1];
            if (arr_access_page.Length > 0)
            { 
                //Delete old access page for group_id
                accountModels.deleteAllPageAccessOfGroup(group_id);
                //create new access page for group_id
                accountModels.createAccessPageforGroup(group_id, arr_access_page);
            }

            string outStr = "" + group_id;
            return Json(outStr);
        }
        #endregion
    }
}
